package com.hmall.item.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.api.domain.dto.ItemDTO;
import com.hmall.api.domain.po.Item;
import com.hmall.api.domain.query.ItemPageQuery;
import com.hmall.common.domain.PageDTO;

import com.hmall.item.service.IItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {

    private final IItemService itemService;
    @Resource
    private  RestHighLevelClient client;
    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        setUp();
        SearchRequest searchRequest=new SearchRequest("items");
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
        if (query.getKey()!=null&&query.getKey()!="") {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if(query.getPageSize()!=null&&query.getPageNo()!=null) {
            searchRequest.source().from((query.getPageNo() - 1) * query.getPageSize());
            searchRequest.source().size(query.getPageSize());
        }
        if(query.getSortBy()!=null&&query.getSortBy()!="") {
            searchRequest.source().sort(query.getSortBy(), SortOrder.DESC);
        }else {
            searchRequest.source().sort("sold",SortOrder.DESC);
        }
        if(query.getCategory()!=null&&query.getCategory()!=""){
            boolQueryBuilder.must(QueryBuilders.matchQuery("category",query.getCategory()));
        }
        if(query.getBrand()!=null) {
            boolQueryBuilder.filter((QueryBuilders.termQuery("brand.keyword", query.getBrand())));
        }

        if(query.getMinPrice()!=null||query.getMaxPrice()!=null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
        }
        searchRequest.source().query(boolQueryBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
//        // 分页查询
//        Page<Item> result = itemService.lambdaQuery()
//                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
//                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
//                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
//                .eq(Item::getStatus, 1)
//                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
//                .page(query.toMpPage("update_time", false));
        // 封装并返回
        tearDown();
        return result(search, query.getPageSize(), query.getPageNo());
//        return PageDTO.of(result(), ItemDTO.class);
    }
    @ApiOperation("搜索分类和品牌")
    @PostMapping("/filters")
    public Map searchBrandOrCategory(@RequestBody ItemPageQuery query) throws IOException {
        setUp();
        SearchRequest searchRequest=new SearchRequest("items");
        searchRequest.source().query(QueryBuilders.matchAllQuery()).size(0);
        if(query.getCategory()!=null&&query.getCategory()!="") {
            searchRequest.source().aggregation(AggregationBuilders.terms("category").field("category.keyword").size(0));
        }
        if(query.getBrand()!=null&&query.getBrand()!="") {
            searchRequest.source().aggregation(AggregationBuilders.terms("brand").field("brand").size(0));
        }
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        Map map = aggResult(search);
        tearDown();
        return map;
    }
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.202.135:9200")
        ));
    }

    @Test
    void testConnect() {
        System.out.println("client: " +client);
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
    private PageDTO<ItemDTO> result(SearchResponse search ,int pageSize,int pageCurrent){
        Page<ItemDTO>page=new Page<>();
        page.setCurrent(pageCurrent);
        page.setSize(pageSize);

        SearchHits hits = search.getHits();
        //long
        page.setTotal(hits.getTotalHits().value);
        SearchHit[] hits1 = hits.getHits();
        List<ItemDTO>items=new ArrayList<>();
        for (SearchHit documentFields : hits1) {
            items.add(JSONUtil.toBean(documentFields.getSourceAsString(),ItemDTO.class));
        }
        page.setRecords(items);
        return PageDTO.of(page,ItemDTO.class);
    }
    private Map aggResult(SearchResponse search){
        Aggregations aggregations = search.getAggregations();

        Terms Categoryaggregation = aggregations.get("category");
        List<? extends Terms.Bucket> Categorybuckets = Categoryaggregation.getBuckets();
        List<String>categorys=new ArrayList<>();

        for (Terms.Bucket bucket : Categorybuckets) {
            categorys.add(bucket.getKey().toString());
        }
        Terms Brandaggregation = aggregations.get("brand");
        List<? extends Terms.Bucket> Brandbuckets = Brandaggregation.getBuckets();
        List<String>brands=new ArrayList<>();

        for (Terms.Bucket bucket : Brandbuckets) {
            brands.add(bucket.getKey().toString());
        }
        Map<String,String> map=new HashMap<>();
        map.put("category",categorys.toString());
        map.put("brand",brands.toString());
        return map;
    }
}
